//全局工具类实现/全局工具类逻辑
import {reqRequest} from '@/api/httpservices'
import {sha256} from 'js-sha256'
const BASE_URL=import.meta.env.VITE_API_URL; 
const mall_Url=import.meta.env.VITE_MALL_URL;

import { userStore } from '@/stores/userStore'

/* 
	 */

/**
 * 请求API公共接口
 *
 * @param url 请求地址
 * @param data 请求数据{}
 * @param method 请求方法 GET/POSt
 * @param header 头部信息
 * @param flag 参数标识 商城
 */
export function Reqeust(url:string,data:any={},method:string, headerType:string = 'application/json;charset=utf-8',flag:string = '') {
	if(method==='POST' || method==='post'){
		data.token=uni.getStorageSync("token") || null;
	}
	let URL = BASE_URL + url
	let options:Recordable = Object.assign({}, {
		url: url,
		data: data,
		method: method,
		header:{
			"content-type":headerType,
			"Authorization":uni.getStorageSync("token")
		}
	})
   return new Promise((resolve, reject) => {
	   //console.warn("data参数..........",data);
	   reqRequest(url,data,options).then((rct)=>{
		   console.warn("Request服务请求返回===>..................",URL,rct);
		   if(rct.data.code===401){
			   let store = userStore();
			   //uni.$tools.Toast("会话超时，请重新登陆")
			   store.$state.hasLogin=false;
			   return uni.$tools.GoUrl("/pages/login/login",0);
		   }
		   resolve(rct);
	   });
	});
}


//签名
function getSign(reqBody:any) {
		var mKeys = Object.keys(reqBody);
		let mSignStr = ''
		if (mKeys.length > 0) {
			mKeys.sort()
			mKeys.forEach(function(val, index) {
				if (val != "sign") {
					if (reqBody[val] !== undefined) {
						if(reqBody[val]===null || reqBody[val]==='undefined' || reqBody[val]==="null" || reqBody[val]==='null'){
							reqBody[val]="";
						}
						if (typeof(reqBody[val]) == "object") {
							reqBody[val] = JSON.stringify(reqBody[val]);
						} 
						mSignStr += val + "=" + reqBody[val] + "&"
					}
				}
			})
			mSignStr += "key=dK@9Zn3ys5@IgHAv" //dK@9Zn3ys5@IgHAv
			//console.log(mSignStr, '拼接')
			mSignStr = sha256(mSignStr).toString();
			return mSignStr;
		}
}


/**
 * 展示加载效果
 *
 * @param show 是否展示
 * @param title 提示信息
 */
function Loading(show: boolean, title = '加载中...') {
  if (show) {
    uni.showLoading({ title });
  } else {
    uni.hideLoading();
  }
}
 
/**
 * 展示提示消息
 *
 * @param title 提示消息
 */
export function Toast(title: string) {
  uni.showToast({
    icon: 'none',
    title
  });
}


/**
 * 获取屏幕宽度
 *
 * @param 
 */
function GetScreenWidth() {
  return uni.getSystemInfoSync().screenWidth;
}


/**
 * 获取屏幕高度
 *
 * @param 
 */
function GetScreenHeigth() {
  return uni.getSystemInfoSync().screenHeight;
}


/**
 * @description url跳转
 */
function GoUrl(url:string,act?:number) {
	if(typeof(act)!='undefined'){
		if(act===0){
			uni.reLaunch({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}		
		if(act===1){
			uni.redirectTo({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}
		if(act===2){
			uni.switchTab({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}
	}else{
		uni.navigateTo({
			url:url,
			fail: function(e){
				console.log("链接发生错误",e);
			}
		})		
	}
}


/**
 * @description 限制字符输出数
 */
function StrLen(str:string,len:number){
	if(str.length>len){
		return str.substring(0,len)+"...";
	}
	return str;
}

/**
 * @description 单位换算
 */

function ComverNumber(num:number){
	if(num>=10000){
		return (Math.round((num/10000)*10)/10)+"万"
	}
	return num;
}

/**
 * @description 浏览量换算
 */
function ComverViewNumber(num:number){
	if(num>=10000){
		return (Math.round((num/10000)*10)/10)+"w"
	}
	return num;
}





/**
 * @description 设置缓存时间
 */
function CacheSet(key:string, value:string, seconds:number) {
	var timestamp =Date.parse(new Date()+"") / 1000;
	if(seconds){
		var expire = timestamp + Number(seconds);
		uni.setStorageSync(key,JSON.stringify(value) + '|' +expire);
		return;
	}
	uni.setStorageSync(key, value);
}

//读取缓存，过期则删除，返回null
function GetCache(key:string){
	var nowTime = Date.parse(new Date()+"") / 1000;
	let val = uni.getStorageSync(key);
	if (val) {
			// 缓存存在，判断是否过期
			let temp = val.split('|')
			if (!temp[1] || temp[1] <= nowTime) {
				uni.removeStorageSync(key)
				return null;
			} else {
				return JSON.parse(temp[0]);
			}
	}
	return null;
}








 
/**
 * 挂在uni简化方案
 */
export default {
  install() {
    if (!uni || typeof uni !== 'object') return;
    uni.$tools = {
	  Reqeust,
      Loading,
      Toast,
	  GetScreenWidth,
	  GetScreenHeigth,
	  GoUrl,
	  StrLen,
	  ComverNumber,
	  ComverViewNumber,
	  CacheSet,
	  GetCache
    };
  }
};